package com.wh.wisdomsite.xbox.us.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wh.wisdomsite.xbox.us.dao.OfficeMapper;
import com.wh.wisdomsite.xbox.us.entity.Office;
import com.wh.wisdomsite.xbox.us.service.ICompanyService;
import com.wh.wisdomsite.xbox.us.service.IOfficeService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 *
 * @author 杨世强
 * @date 10:56 2018/8/6
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
@Service("officeService")
@Transactional(rollbackFor = {Exception.class, RuntimeException.class})
public class OfficeServiceImpl extends ServiceImpl<OfficeMapper, Office> implements IOfficeService {

    private static final Log logger = LogFactory.getLog(OfficeServiceImpl.class);

    @Autowired
    private OfficeMapper officeMapper;

    @Autowired
    private ICompanyService iCompanyService;

    @Override
    public Page<Office> getPage(Page<Office> page,Wrapper<Office> wrapper){
        SqlHelper.fillWrapper(page, wrapper);
        page.setRecords(this.baseMapper.getPageList(page, wrapper));
        return page;
    }

    @Override
    public Office getOfficeById(Integer id) {
        return officeMapper.getById(id);
    }

    @Override
    public List<Office> getList(Wrapper<Office> var1) {
        return officeMapper.getList(var1);
    }

    @Override
    public List<Office> getMenuListForSerch(List<Office> parentList){
        List<Office> treeOfficeList = new ArrayList<Office>();
        int num = parentList.size();
        for(int i =0;i<num;i++){
            Map map = new HashMap();
            List<Integer> officeIds = new ArrayList<Integer>();
            Map mapResult = getNodeFloorTree(parentList.get(i),parentList,officeIds,map);
            Office office = (Office) mapResult.get("office");
            List<Integer> officeIdResult = (List<Integer>) mapResult.get("officeIds");
            treeOfficeList.add(office);
            // 先从集合中移除当前对象
            parentList.remove(i);
            i--;
            num--;
            // 再从集合中移除当前对象的子集
            int num1 = parentList.size();
            for(int j=0;j<num1;j++){
                boolean equalFlag = false;
                for(Integer officeId : officeIdResult){
                    if(parentList.get(j).getOfficeId().equals(officeId)){
                        parentList.remove(j);
                        equalFlag = true;
                        num--;
                        num1--;
                    }
                }
                if(equalFlag){
                    j--;
                }
            }
        }
        return treeOfficeList;
    }

    /**
     * 获取当前节点的树形结构，同时返回此节点树的主键，用作父方法从集合中去掉对应的对象
     * @param office
     * @param officeList
     * @param officeIds
     * @param map
     * @return
     */
    Map getNodeFloorTree(Office office,List<Office> officeList,List<Integer> officeIds,Map map){
        Integer officeIdPr = office.getOfficeId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(null != officeIdPr){
            office.setCreateDateFormat(office.getCreateDate()==null?"":sdf.format(office.getCreateDate()));
            List<Office> officeCh = new ArrayList<Office>();
            for(Office office1 : officeList){
                Integer officeIdCh = office1.getParentId();
                if(officeIdPr.equals(officeIdCh)){
                    office1.setCreateDateFormat(office1.getCreateDate()==null?"":sdf.format(office1.getCreateDate()));
                    officeCh.add(office1);
                    officeIds.add(office1.getOfficeId());
                    getNodeFloorTree(office1,officeList,officeIds,map);
                }
            }
            office.setChildren(officeCh);
            map.put("office",office);
            map.put("officeIds",officeIds);
        }
        return map;
    }

    /**
     * 递归获取部门树形结构
     *
     * @param parentOfficeList
     * @param officeList
     * @return
     */
    private List<Office> getChildren(List<Office> parentOfficeList, List<Office> officeList) {
        for (Office office : parentOfficeList) {
            List<Office> childrenOfficeList = new ArrayList<>();
            for (Office OfficeChild : officeList) {
                if (OfficeChild.getParentId().equals(office.getOfficeId())) {
                    childrenOfficeList.add(OfficeChild);
                }
            }
            office.setChildren(childrenOfficeList);
            //迭代添加子菜单
            getChildren(childrenOfficeList, officeList);
        }
        return parentOfficeList;
    }


    @Override
    public String getOfficeCode(List<Office> officeList, Integer parentId, String compCode) {
        String officeCodeResult = "";
        //存在父级部门，构造子集编码；不存在则构建父级编码
        if (null != parentId && Integer.valueOf(parentId) > 0) {
            EntityWrapper<Office> ewOfficeCh = new EntityWrapper<Office>();
            ewOfficeCh.eq("off.parentId", parentId);
            ewOfficeCh.eq("off.dataState", "1");
            List<Office> officeListCh = officeMapper.getList(ewOfficeCh);
            //是否存在子集，构造不同的编码
            if (null != officeListCh && officeListCh.size() > 0) {
                //寻找最大编码,并加一
                String maxCode = getMaxCode(officeListCh);
                officeCodeResult = compCode + "-" + maxCode;
            } else {
                Office office1 = officeMapper.getById(parentId);
                String officeCode = office1.getOfficeCode();
                officeCodeResult = officeCode + "000";
            }
        } else {
            //没有选择父级部门，直接在公司下添加直属部门
            String maxCode = getMaxCode(officeList);
            officeCodeResult = compCode + "-" + maxCode;
        }
        return officeCodeResult;
    }

    /**
     * 构造最大编码
     * @param officeList
     * @return
     */
    String getMaxCode(List<Office> officeList){
        String maxCode = "0";
        for(Office officeSerch : officeList){
            String[] officeCodeSp = officeSerch.getOfficeCode().split("-");
            //获取"-"后的编码,并值选取编码只有三位的
            String officeCode1 = officeCodeSp[1];
            int compareResult = officeCode1.compareTo(maxCode);
            if (compareResult > 0) {
                maxCode = officeCode1;
            }
        }
        // 获取编码最后三位数
        String maxCode1 = maxCode.substring(maxCode.length() - 3,maxCode.length());
        // 需要在获取的三位数前加上"1",避免字符转换为数字时变为"0"
        String structCode = "1"+maxCode1;
        // 给编码加一
        String maxCode2 = String.valueOf(Integer.valueOf(structCode)+1);
        // 将构造的四位编码去掉首位，变为需要的三位编码
        String structCode1 = maxCode2.substring(1,maxCode2.length());
        // 获取最大编码除去最后三位
        String maxCode3 = maxCode.substring(0,maxCode.length() - 3);
        // 将构造的编码组合，得到最终编码
        String maxCode4 = maxCode3 + structCode1;
        return maxCode4;
    }

    @Override
    public JSONArray toTreeOffice(List<Office> allOfficeList,Boolean isAdmin) throws Exception {
        JSONArray jsonArray = new JSONArray();
        int oneNode = 1;
        int codeLengthOne = 0;
        //先装载根节点
        for (Office office : allOfficeList) {
            if(isAdmin){
                if (office.getParentId().equals(0)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", office.getOfficeId());
                    jsonObject.put("text", office.getName());
                    jsonArray.put(jsonObject);
                }
            }else{
                if(oneNode==1){
                    codeLengthOne = office.getOfficeCode().length();
                    oneNode ++ ;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", office.getOfficeId());
                    jsonObject.put("text", office.getName());
                    jsonArray.put(jsonObject);
                }else{
                    int codeLength = office.getOfficeCode().length();
                    if(codeLength == codeLengthOne){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", office.getOfficeId());
                        jsonObject.put("text", office.getName());
                        jsonArray.put(jsonObject);
                    }
                }
            }
        }
        //传入根节点,装载其子节点
        jsonArray = loadTreeChildren(jsonArray, allOfficeList);
        return jsonArray;
    }

    private JSONArray loadTreeChildren(JSONArray parentJsonArray, List<Office> officeList) throws Exception {
        for (int i = 0; i < parentJsonArray.length(); i++) {
            JSONObject obj = parentJsonArray.getJSONObject(i);
            Integer officeId = (Integer) obj.get("id");
            JSONArray childrenOfficeArray = new JSONArray();
            for (Office officeCh : officeList) {
                if (officeCh.getParentId().equals(officeId)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", officeCh.getOfficeId());
                    jsonObject.put("text", officeCh.getName());
                    childrenOfficeArray.put(jsonObject);
                }
            }
            obj.put("children", childrenOfficeArray);
            //迭代加载子部门
            loadTreeChildren(childrenOfficeArray, officeList);
        }
        return parentJsonArray;
    }

    @Override
    public void updateChildNode(Office office,Integer sessionCompId) {
        EntityWrapper<Office> ewOffice = new EntityWrapper<Office>();
        ewOffice.setEntity(new Office());
        if(null != sessionCompId){
            ewOffice.eq("off.companyId",sessionCompId);
        }
        ewOffice.eq("off.dataState","1");
        ewOffice.orderBy("off.officeCode",true);
        // 获取部门数据
        List<Office> allOfficeList = officeMapper.getList(ewOffice);
        List<Office> parentOffice = new ArrayList<Office>();
        parentOffice.add(office);
        // 获取当前节点及以下所有子节点
        List<Office> treeOfficeList = getChildren(parentOffice, allOfficeList);
        // 获取子集
        List<Office> getChildrenList = treeOfficeList.get(0).getChildren();
        if(getChildrenList.size() > 0){
            updateChildCode1(office.getOfficeCode(),getChildrenList);
        }
    }

    @Override
    public Map<String, Object> getMapById(Serializable id) {
        return officeMapper.getMapById(id);
    }

    /**
     * 更新节点对象的子集编码步骤1
     * @param officeCode
     * @param officeList
     */
    void updateChildCode1(String officeCode,List<Office> officeList){
        for(int i=0;i<officeList.size();i++){
            Integer structCode = 1000;
            // 给初始编码加编号
            String maxCode = String.valueOf(structCode+i);
            // 将构造的四位编码去掉首位，变为需要的三位编码
            String structCode1 = maxCode.substring(1,maxCode.length());
            // 构造当前对象的子集编码
            String structCode2 = officeCode + structCode1;
            Office office = officeList.get(i);
            office.setOfficeCode(structCode2);
            officeMapper.updateById(office);
            List<Office> officeList1 = office.getChildren();
            if(officeList1.size() > 0){
                updateChildCode1(structCode2,officeList1);
            }
        }
    }
}




